#include "cpu/exec.h"

// static OpcodeEntry csrop_table [8] = {
//   EXW(einst,0), EXW(csrrw,4) , EXW(csrrs,4), EXW(csrrc,4), EMPTY, EXW(csrrw,4), EXW(csrrs,4), EXW(csrrc,4)
// };
// static inline void rtl_csrr(rtlreg_t* dest, int r, int width) ;
// static inline void rtl_csrw(int r, const rtlreg_t *src1, int width)
//ecall sret
make_EHelper(einst) { 
    // Log("einst instruction");/
    if(decinfo.isa.instr.imm31_12 == 0) { //ecall
        // Log("ecall instruction");
        rtl_csrwi(CSR_SCAUSE,0x09,4);
        rtl_csrwi(CSR_SSTATUS,0x03,4);
        // rtl_csrw(CSR_SEPC,pc,4);
        rtl_csrwi(CSR_SEPC,*pc - 4,4);
        
        rtl_csrr(&s0,CSR_STVEC,4);
        rtl_j(s0);
    }else if(decinfo.isa.instr.rs2 == 2 && decinfo.isa.instr.funct7 == 8) { //SRET
        // Log("sret instruction");
        rtl_csrr(&s0,CSR_SEPC,4);
        rtl_j(s0);
    }
}

make_EHelper(csrrw) {
    // Log("CSR RW");
    rtl_csrr(&s0,decinfo.isa.instr.simm11_0,4);
    rtl_sr(id_dest->reg, &s0, 4);
    rtl_csrw(decinfo.isa.instr.simm11_0,&(id_src->val),4);
}

make_EHelper(csrrs) {
    // Log("CSR Set");
    rtl_csrr(&s0,decinfo.isa.instr.simm11_0,4);
    rtl_sr(id_dest->reg, &s0, 4);
    rtl_set(&s1,&s0,&(id_src->val));
    rtl_csrw(decinfo.isa.instr.simm11_0,&s1,4);
}

make_EHelper(csrrc) {
    Log("CSR Read clear");
    rtl_csrr(&s0,decinfo.isa.instr.simm11_0,4);
    rtl_sr(id_dest->reg, &s0, 4);
    rtl_clear(&s1,&s0,&(id_src->val));
    rtl_csrw(decinfo.isa.instr.simm11_0,&s1,4);
}

